﻿using Aop.Api;
using Coldairarrow.Business.Backstage.UserData;
using Coldairarrow.Entity.Backstage.UserData;
using Coldairarrow.Entity.Frontstage.BS_TransferLog;
using Coldairarrow.Entity.Pay;
using Coldairarrow.IBusiness;
using Coldairarrow.Util;
using Coldairarrow.Util.Pay.AlipayPay;
using EFCore.Sharding;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Serilog;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;

namespace Coldairarrow.Api.Controllers.Pay
{
    [Route("/PayTransfer/[controller]/[action]")]
    public class AlipayTransferController : BaseApiController
    {
        private IDbAccessor _DB;
        private readonly IOperator _Operator;
        public readonly IBS_UserRebateBusiness _UserRebateBusiness;
        public readonly IWebHostEnvironment _webHostEnvironment;
        public AlipayTransferController(IDbAccessor db, IOperator Operator, IBS_UserRebateBusiness UserRebateBusiness, IWebHostEnvironment hostEnvironment)
        {
            _DB = db;
            _Operator = Operator;
            _UserRebateBusiness = UserRebateBusiness;
            _webHostEnvironment = hostEnvironment;
        }


        public class AliRefundDTO { 
            /// <summary>
            /// 支付宝账户名/邮箱/绑定手机号
            /// </summary>
            [Required]
            public string AliName { set; get; }

            /// <summary>
            /// 提现金额
            /// </summary>
            [Required]
            public decimal Amount { set; get; }

            /// <summary>
            /// 用户名称
            /// </summary>
            [Required]
            public string UserName { set; get; }

            /// <summary>
            /// IP地址
            /// </summary>
            [Required]
            public string IP { set; get; }
        }


        /// <summary>
        /// 提现
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<Object> AlipayTransferMoney(AliRefundDTO input)
        {
            #region//获取今日可提现额
            decimal txMoney = input.Amount;

            var sumData = _UserRebateBusiness.GetMyCanTransData();
            //获取个人收益合计
            var upMList = _DB.GetIQueryable<BS_UserICPoint>().Where(x => x.UserId.Equals(_Operator.UserId)).ToList();

            if (upMList.Count == 0)
            {
                throw new BusException("个人收益信息查询失败，提现失败！");
            }
            else if (upMList[0].Income < input.Amount)
            {
                throw new BusException("提现金额大于收益金额，提现失败！");
            }
            else if (input.Amount < 0.1M)
            {
                throw new BusException("提现金额不能小于0.1元！");
            }
            //input.Amount = 0.1M;
            if (sumData < input.Amount)
            {
                throw new BusException("提现金额大于今日可提现金额，提现失败！");
            }

            
            //创建提现记录
            BS_Transfer tModel = new BS_Transfer();
            tModel.Id = IdHelper.GetId();
            tModel.CreateTime = DateTime.Now;
            tModel.Deleted = false;
            tModel.CreatorId = _Operator.UserId;
            tModel.UserId = _Operator.UserId;
            tModel.TXUserInfo = input.AliName;
            tModel.Type = 1; //支付宝提现
            tModel.Amount = input.Amount;
            tModel.UserName = input.UserName;
            tModel.IPInfo = input.IP;
            tModel.Time = DateTime.Now;

            //创建收益提现记录
            BS_UserRebate urModel = new BS_UserRebate();
            urModel.Id = IdHelper.GetId();
            urModel.Deleted = false;
            urModel.CreatorId = _Operator.UserId;
            urModel.CreateTime = DateTime.Now;
            urModel.SUserId = _Operator.UserId;
            urModel.Note =  "主动提现：-" + input.Amount.ToString("0.00") + "收益";
            urModel.OrderMoney = 0.00M;
            urModel.ReturnDiscount = 0;
            urModel.Type = 2;
            urModel.ReturnMoney = -1 * input.Amount;

            //减去个人收益
            upMList[0].Income -= input.Amount;
            #endregion

            var rootPath = _webHostEnvironment.WebRootPath;
            Log.Information(".ContentRootPathpath=" + _webHostEnvironment.ContentRootPath);
            var cert =new Config.certParams();
            //设置证书相关参数
            CertParams certParams = new CertParams
            {
                AlipayPublicCertPath =_webHostEnvironment.WebRootPath + cert.AlipayPublicCertPath,
                AppCertPath = _webHostEnvironment.WebRootPath + cert.AppCertPath,
                RootCertPath = _webHostEnvironment.WebRootPath + cert.RootCertPath
            };

            //input.Amount = 0.1M;
            var response = AliTransfer.AlipayRefundMoney(Config.AppId, Config.PrivateKey, Config.AlipayPublicKey, certParams, tModel.Id,input.Amount,input.AliName,input.UserName);
            Log.Information("s1="+response.ToJson().ToString());
            if (response.Code == "10000")
            {
                upMList[0].Income -= input.Amount;
                tModel.State = 1;
                await _DB.InsertAsync(tModel);
                await _DB.InsertAsync(urModel);
                await _DB.UpdateAsync(upMList[0]);
                var obj = new
                {
                    InputAmount = txMoney,
                    TranAmount = input.Amount,
                    TOderId = tModel.Id
                };

                return obj;
            }
            else
            {
                tModel.State = -1;
                await _DB.InsertAsync(tModel);
                Log.Information(response.ToJson().ToString());
                throw new BusException("提现失败,请检查提款金额后重试，若再次报错请联系客服！");
            }
        }
    }
}
